const Koa = require("koa");
const KoaRouter = require("koa-router");
const bodyparser = require("koa-bodyparser");
const { query } = require("./util");

// 创建一个 Web 实例
const app = new Koa();

// 创建 KoaRouter 实例
const router = new KoaRouter();

// 使用 KoaRouter 定义 Web 接口
router.get("/users", async (ctx) => {
    // 拿到了分页参数
    const { pagenum, pagesize } = ctx.query;
    let sql = "select * from user limit ?, ?";
    let params = [(pagenum - 1) * pagesize, Number(pagesize)];
    let list = await query(sql, params);
    // 计数
    let res = await query("select count(0) as count from user");
    const total = res[0].count;
    ctx.body = {
        code: 200,
        data: {
            list,
            total,
        },
        message: "获取用户列表成功",
    };
});

router.post("/users", async (ctx) => {
    // 接收前端发送过来的请求数据
    const { username, password, mobile, email, age, sex } = ctx.request.body;
    // 发送 SQL 语句到服务器，保存到 user 表中
    let res = await query(
        "insert into user (username, password, mobile, email, age, sex) values (?, ?, ?, ?, ?, ?)",
        [username, password, mobile, email, age, sex]
    );
    // 判断是否插入成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: "添加用户失败",
        };
        return;
    }
    // 返回成功响应
    ctx.body = {
        code: 201,
        message: "用户信息保存成功",
    };
});

router.put("/users/:id", async (ctx) => {
    // 获取路径参数
    const { id } = ctx.params;
    // 获取请求参数
    const { username, password, mobile, email, age, sex } = ctx.request.body;
    // 查询用户是否存在
    let res = await query("select * from user where id = ?", [id]);
    if (res.length === 0) {
        ctx.body = {
            code: 404,
            message: "要修改的用户不存在",
        };
        return;
    }
    // 拿到该用户
    let user = res[0];
    // 修改用户信息
    let params = [
        username ? username : user.username,
        password ? password : user.password,
        mobile ? mobile : user.mobile,
        email ? email : user.email,
        age ? age : user.age,
        sex ? sex : user.sex,
        id,
    ];
    res = await query(
        "update user set username = ?, password = ?, mobile = ?, email = ?, age = ?, sex = ? where id = ?",
        params
    );
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: "修改失败",
        };
        return;
    }
    ctx.body = {
        code: 200,
        message: "用户信息修改成功",
    };
});

router.delete("/users/:id", async (ctx) => {
    // 获取路径参数
    const { id } = ctx.params;
    // 直接删除
    let res = await query("delete from user where id = ?", [id]);
    // 判断是否删除成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: "用户删除失败",
        };
        return;
    }
    // 返回成功响应
    ctx.body = {
        code: 204,
        message: "用户删除成功",
    };
});

// 使用 koa-bodyparser 中间件
app.use(bodyparser());

// 挂载路由
app.use(router.routes());

// 监听端口，提供服务
app.listen(9000, () => {
    console.log("Koa server running at http://localhost:9000");
});
